package com.company.test16;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Created by Administrator on 2016.6.12.
 */
public class Test16_06 extends JFrame {
    private JTextField jtfAnnualInterestRate=new JTextField();
    private JTextField jtfNumberOfYears=new JTextField();
    private JTextField jtfLoanAmount=new JTextField();
    private JTextField jtfMonthlyPayment=new JTextField();
    private JTextField jtfTotalPayment=new JTextField();

    private JButton jbtComputeLoan=new JButton("Compute Payment");

    public Test16_06(){
        JPanel p1=new JPanel(new GridLayout(5,2));
        p1.add(new JLabel("Annual Interest Rate"));
        p1.add(jtfAnnualInterestRate);
        p1.add(new JLabel("Number of Years"));
        p1.add(jtfNumberOfYears);
        p1.add(new JLabel("LoanAmount"));
        p1.add(jtfLoanAmount);
        p1.add(new JLabel("MonthlyPayment"));
        p1.add(jtfMonthlyPayment);
        p1.add(new JLabel("TotalPayment"));
        p1.add(jtfTotalPayment);
        p1.setBorder(new TitledBorder("Enter loan amount, interest rate, and year"));

        JPanel p2=new JPanel(new FlowLayout(FlowLayout.RIGHT));
        p2.add(jbtComputeLoan);

        add(p1,BorderLayout.CENTER);
        add(p2,BorderLayout.SOUTH);

        jbtComputeLoan.addActionListener(new ButtonListener());
    }

    private class ButtonListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            double interest=Double.parseDouble(jtfAnnualInterestRate.getText());
            int year=Integer.parseInt(jtfNumberOfYears.getText());
            double loanAmount=Double.parseDouble(jtfLoanAmount.getText());

            interest=interest/12;

            double monthlyPayment=(loanAmount*interest/100)/((1-interest/100)*
                    (1-Math.pow(1-interest/100,12*year)));

            double totalPayment=monthlyPayment*12*year;

            jtfMonthlyPayment.setText(String.format("%.2f",monthlyPayment));
            jtfTotalPayment.setText(String.format("%.2f",totalPayment));

        }
    }

    public static void main(){
        Test16_06 frame=new Test16_06();
        frame.setTitle("贷款计算器");
        frame.setLocationRelativeTo(null);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}